/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.R;
import gr.ebs.gssdroid.async.GssAsyncTask;
import gr.ebs.gssdroid.async.TaskResult;
import gr.ebs.gssdroid.http.GssHttpCommands;
import gr.ebs.gssdroid.http.GssHttpException;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.FileResource;
import gr.ebs.gssdroid.resource.FolderResource;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.resource.TrashResource;
import gr.ebs.gssdroid.widget.CustomListAdapter;
import gr.ebs.gssdroid.widget.CustomListView;
import gr.ebs.gssdroid.widget.MyFoldersListAdapter;
import gr.ebs.gssdroid.widget.TrashListAdapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

public class GssTrash extends GssMyFolders {
TrashListAdapter adapter;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.getItem(3).setEnabled(false);
		return true;
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
		newButton.setVisibility(View.INVISIBLE);
	}

	@Override
	protected void initialize() {
		adapter = new TrashListAdapter((Activity) this, R.layout.row, new ArrayList<RestResource>());
		((CustomListView) findViewById(R.id.fileListView)).setAdapter(adapter);
		if(getDroidApplication().getUserResource()==null||getDroidApplication().getUserResource().getFilesPath()==null){
			handleLogin();
			finish();
			return;
		}
		getTrashTask().execute(getDroidApplication().getUserResource().getTrashPath());
	}

	@Override
	protected void onEntrySelected(int position, RestResource resource) {

	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	protected void populateList(RestResource data) {
		ArrayList<RestResource> dataList = new ArrayList<RestResource>();
		dataList.addAll(((TrashResource) data).getFolders());
		dataList.addAll(((TrashResource) data).getFiles());
		adapter.setListItems(dataList);
		adapter.notifyDataSetChanged();
		((TextView) findViewById(R.id.textPath)).setText("My Trash");

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		final RestResource entry = adapter.getItem(((AdapterContextMenuInfo) menuInfo).position);
		inflater.inflate(R.menu.foldercontextmenu, menu);
		for (int i = 0; i < menu.size(); i++) {
			if (menu.getItem(i).getItemId() == R.id.deleteFolder || menu.getItem(i).getItemId() == R.id.restoreFolder)
				menu.getItem(i).setVisible(true);
			else
				menu.getItem(i).setVisible(false);
		}

		/*
		 * AdapterView.AdapterContextMenuInfo info =
		 * (AdapterView.AdapterContextMenuInfo) menuInfo; GssFileListAdapter
		 * adapt = (GssFileListAdapter) ((GssFileListView)
		 * findViewById(R.id.fileListView)) .getAdapter(); final
		 * GssFileListAdapterEntry entry = adapt.getItem(info.position); //
		 * if(entry.file instanceof FolderResource)
		 */

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		final RestResource entry = adapter.getItem(info.position);
		AlertDialog alertDialog = null;
		switch (item.getItemId()) {
		case R.id.restoreFolder:
			alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Restore Folder");
			alertDialog.setMessage("R u sure you want to restore this folder and all its children?");
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					restoreFolderTask().execute(entry.getUri());
				}
			});
			alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			alertDialog.setCancelable(true);
			alertDialog.show();
			return true;
		}
		// TODO Auto-generated method stub
		return super.onContextItemSelected(item);
	}

	private GssAsyncTask getTrashTask() {
		GssAsyncTask getTrashTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssTrash.this, "Fetching Data", "Please Wait", true, false);
				// if(myprogress==null || !myprogress.isShowing()){

				// }
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				return new GssHttpCommands(getDroidApplication().getUserDetails()).getTrashResource(params[0]);
			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getResource() != null)
					populateList((TrashResource) result.getResource());
				else if (result.getException() != null)
					handleRestException("TRASH", result.getException());
				super.onPostExecute(result);
			}
		};
		return getTrashTask;
	}

	private GssAsyncTask restoreFolderTask() {
		GssAsyncTask getFolderTask = new GssAsyncTask(getDroidApplication().getUserDetails()) {
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				myprogress = ProgressDialog.show(GssTrash.this, "Fetching Data", "Please Wait", true, false);
			}

			@Override
			protected RestResource doExecution(String[] params) throws Exception {
				new GssHttpCommands(getDroidApplication().getUserDetails()).restoreFolderFromTrash(params[0]);
				return null;

			}

			@Override
			protected void onPostExecute(TaskResult result) {
				myprogress.hide();
				if (result.getException() == null)
					getTrashTask().execute(getDroidApplication().getUserResource().getTrashPath());
				else
					handleRestException("TRASH", result.getException());
				super.onPostExecute(result);
			}
		};
		return getFolderTask;
	}

	protected void refresh() {
		getTrashTask().execute(getDroidApplication().getUserResource().getTrashPath());
	}
	
	@Override
	protected CustomListAdapter<RestResource> getAdapter() {

		return adapter;
	}
}
